package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.model.jsonObject.ApproveSubWork;
import com.powerunion.datacollection.model.jsonObject.RoleTreeNode;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameterSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class TasksViewDaoImpl extends JdbcBase  {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			TasksViewDaoImpl.class);

	public List findPendingTasksByUser(String userCode) throws DaoException {
		return null;
	}
		

	/**
	 * 查找该用户当前的审批任务
	 * 
	 * @param userCode
	 * @return
	 */
	public List findApproveWorkByUser(String userCode) {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,s.act_id,s.aw_type,")
				.append(
						"s.staff_id,s.date_approve,s.aw_state,s.approve_info,s.pre_act_id,s.submi_user, ")
				.append(
						" s.form_id from dc_item_info t left join dc_approve_work s on s.proc_id = t.id ")
				.append(
						" left join dc_wf_instance w on t.id = w.proc_id  where s.staff_id = ? and s.aw_state <>  5")
				.append(
						"  and s.aw_state <> 4 and s.aw_state <> 6 and s.aw_state <> 2 and s.aw_state <> 8 and s.aw_state <> 9 ");

		List spproveWorkList = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			spproveWorkList = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					int j = 0;
					ApproveWorkItem awi = new ApproveWorkItem();
					awi.setId(rs.getFieldValueAsString(j++));
					awi.setProcId(rs.getFieldValueAsString(j++));
					awi.setProcName(rs.getFieldValueAsString(j++));
					awi.setTaskDesc(rs.getFieldValueAsString(j++));
					awi.setTaskName(rs.getFieldValueAsString(j++));
					awi.setActId(rs.getFieldValueAsString(j++));
					awi.setType(rs.getFieldValueAsInteger(j++).intValue());
					awi.setStaffId(rs.getFieldValueAsString(j++));
					Date timeLimit = rs.getFieldValueAsDate(j++);
					String timeLitmitStr = Format.getInstance().dateToYMD(
							timeLimit);
					awi.setTimeLimitStr(timeLitmitStr);
					awi.setState(rs.getFieldValueAsInteger(j++).intValue());
					awi.setApproveInfo(rs.getFieldValueAsString(j++));
					awi.setPreActId(rs.getFieldValueAsString(j++));
					awi.setSubmiUser(rs.getFieldValueAsString(j++));
					awi.setFormId(rs.getFieldValueAsString(j++));

					spproveWorkList.add(awi);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的当前审批任务失败！", e);
			return null;
		}

		return spproveWorkList;
	}

	/**
	 * 更新审批明细状态
	 * 
	 * @param state
	 * @param actId
	 * @return
	 */
	public boolean updateState4Act(int state, String actId) throws DaoException {
		String sql = "update dc_approve_work set aw_state=? where act_id= ? and aw_state<>8 ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.INTEGER,
				new Integer(state)));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, actId));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("更新环节id为：" + actId + " 的审批明细状态失败！", e);
			throw new DaoException("更新环节id为：" + actId + " 的审批明细状态失败！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState4Act:" + Constants.UPDATE + "审批明细状态"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.UPDATE + "审批明细状态"
						+ Constants.FAIL);
			}
			return false;
		}

	}

	public boolean updateState4User(int state, String id) throws DaoException {
		String sql = "update dc_approve_work set aw_state=? where id = ? and aw_state<>8 ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.INTEGER,
				new Integer(state)));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, id));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("更新审核任务id为：" + id + " 的审核明细状态失败！", e);
			throw new DaoException("更新审核任务id为：" + id + " 的审核明细状态失败！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState4User:" + Constants.UPDATE
						+ "审核任务id为：" + id + " 的审核明细状态" + Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState4User:" + Constants.UPDATE
						+ "审核任务id为：" + id + " 的审核明细状态" + Constants.FAIL);
			}
			return false;
		}

	}

	public boolean hideApproveWork(String actId, String approveWorkId,
			String preActId) throws DaoException {
		String sql = "update dc_approve_work set aw_state=8 where act_id = ? and id <> ? and pre_act_id=? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, approveWorkId));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, preActId));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("隐藏环节id为：" + actId + " 的审核任务失败！", e);
			throw new DaoException("隐藏环节id为：" + actId + " 的审核任务失败！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("hideApproveWork:" + "隐藏环节id为：" + actId + " 的审核任务"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("hideApproveWork:" + "隐藏环节id为：" + actId + " 的审核任务"
						+ Constants.FAIL);
			}
			return false;
		}

	}

	public boolean hideAllApproveWork(String preActId) throws DaoException {
		String sql = "update dc_approve_work set aw_state=8 where pre_act_id = ?";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.VARCHAR, preActId));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("隐藏报送环节id为：" + preActId + " 的审核任务失败！", e);
			throw new DaoException("隐藏报送环节id为：" + preActId + " 的审核任务失败！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("hideApproveWork:" + "隐藏报送环节id为：" + preActId
						+ " 的审核任务" + Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("hideApproveWork:" + "隐藏报送环节id为：" + preActId
						+ " 的审核任务" + Constants.FAIL);
			}
			return false;
		}

	}

	public boolean resumeApproveWork(String procId) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("update dc_approve_work set aw_state = ")
				.append(
						"(select state_track from dc_approve_work where id = ?) where id = ?");
		Connection conn = null;
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql.toString());
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		try {
			conn = this.getConnection();
			List ids = this.findApproveWorkIdByProcId(procId, conn);
			if (ids != null && ids.size() > 0) {
				for (Iterator iter = ids.iterator(); iter.hasNext();) {
					SqlParameterSet spSet = new SqlParameterSet();
					String id = (String) iter.next();
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));

					update.addBatchParameter(spSet);
				}
				update.access();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("resumeApproveWork error!");
		}
		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("resumeApproveWork success!");
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("resumeApproveWork failure!");
			}
			return false;
		}
	}

	public boolean suspendApproveWork(String procId) throws DaoException {
		String sql = "update dc_approve_work set aw_state=6 where proc_id =? and aw_state <> 8";
		Connection conn = null;
		PreparedStatement ps = null;
		boolean flag = false;
		try {
			conn = this.getConnection();

			List ids = this.findApproveWorkIdByProcId(procId, conn);
			this.backupState(ids, conn);

			// 更改报送明细表状态
			ps = conn.prepareStatement(sql);
			ps.setString(1, procId);
			ps.executeUpdate();
			flag = true;
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("suspendApproveWork error!");
		} finally {
			DBUtils.close(ps, conn);
		}
		return flag;
	}

	private boolean backupState(List ids, Connection conn) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("update dc_approve_work set state_track= ")
				.append(
						"(select aw_state from dc_approve_work where id = ?) where id = ?");
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql.toString());
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		try {
			if (ids != null && ids.size() > 0) {
				for (Iterator iter = ids.iterator(); iter.hasNext();) {
					SqlParameterSet spSet = new SqlParameterSet();
					String id = (String) iter.next();
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));

					update.addBatchParameter(spSet);
				}
				update.access();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("backupState error!");
		}
		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("backupState success!");
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("backupState failure!");
			}
			return false;
		}

	}

	private List findApproveWorkIdByProcId(String procId, Connection conn)
			throws DaoException {
		String sql = "select id from dc_approve_work where proc_id = ?";

		QueryOperator query = new QueryOperator();
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.setSql(sql);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, procId));
		List list = null;
		try {

			list = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					String id = rs.getFieldValueAsString("id");

					list.add(id);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("findApproveWorkIdByProcId error!");
		}
		return list;
	}

	public List findApproveWorkIdByActivityId(String activityId)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select a.id,a.staff_id,a.aw_state,f.user_name  from dc_approve_work a ")
				.append(
						" left join frameuser f on a.staff_id=f.user_code  where a.act_id = ? and a.aw_state<>8");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, activityId));
		List list = null;
		try {
			list = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					RoleTreeNode treeNode = new RoleTreeNode();
					String id = rs.getFieldValueAsString("id");
					treeNode.setId(id);
					int state = rs.getFieldValueAsInteger("aw_state")
							.intValue();
					String stateStr = "";
					switch (state) {
					case 1:
						stateStr = "已填写未提交";
						break;
					case 2:
						stateStr = "等待其他人";
						break;
					case 3:
						stateStr = "超时未完成";
						break;
					case 4:
						stateStr = "等待审批中";
						break;
					case 5:
						stateStr = "完成审批";
						break;
					default:
						stateStr = "未处理";
						break;
					}
					String userName = rs.getFieldValueAsString("user_name");
					String text = userName + "&lt;" + stateStr + "&gt;";
					treeNode.setText(text);
					treeNode.setLeaf(true);
					treeNode.setIconCls("workGroup");

					list.add(treeNode);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("findApproveWorkIdByProcId error!");
		}
		return list;
	}

	/**
	 * 判断是否能提交报送数据到上级审批步骤
	 * 
	 * @param procId
	 * @param actId
	 * @return
	 * @throws DaoException
	 */
	public boolean submissionRule(String actId) throws DaoException {
		Connection conn = null;
		boolean flag = false;
		try {
			conn = this.getConnection();

			int actType = this.getActivityType(actId);
			if (actType == Constants.APPROVE_TYPE_SINGLE) {// 单人型
				/**
				 * 单人类型 需要判断该环节的其他人是否已经提交过了， 如果已经有人提交过了则不能提交
				 */
				int count = this.getCountActivityComplete(actId, conn);
				if (count > 0) {
					flag = false;
				} else {
					flag = true;
				}
			} else if (actType == Constants.APPROVE_TYPE_MULTI) {// 多人型
				int totalWaitingUser = this
						.getCountActivityWaiting(actId, conn);
				int totalActUser = this.getCountActivityTotalUser(actId, conn);
				// 当其他人都已经填写完审批意见处于等待状态的情况下就可以提交到上级节点去
				if (totalWaitingUser == totalActUser - 1) {
					flag = true;
				} else {
					flag = false;
				}
			} else if (actType == Constants.START_STEP_TYPE) {
				return true;
			}

		} catch (Exception e) {
			logger.error("", e);
		} finally {
			DBUtils.close(conn);
		}
		return flag;
	}

	private int getCountActivityComplete(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select count(id) c from dc_approve_work where act_id = ? ")
				.append(
						" and aw_state <> 0 and aw_state <> 1 and aw_state <> 2 and aw_state <> 3")
				.append(
						" and aw_state <> 6 and aw_state <> 7 and aw_state <> 8 and aw_state <> 9");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityComplete error!");
		}
		return count;
	}

	/**
	 * 判断是否所有的子节点都已经上报了数据
	 * 
	 * @param actId
	 * @return
	 * @throws DaoException
	 */
	public boolean isAllSubActHaveSubmission(String actId) throws DaoException {
		Connection conn = null;
		boolean flag = false;
		try {
			conn = this.getConnection();
			// 得到在流程实例中的子节点的个数
			int subActivityCount = this.getCountSubActInProcess(actId, conn);
			int preActCount = this.getCountPreAct(actId, conn);
			// 如果上报的子节点个数与在流程中的子节点数一样，说明所有的子节点都已经上报了，则接下来可以根据步骤类型判断是否允许提交上报
			if (preActCount == subActivityCount) {
				flag = true;
			} else {
				flag = false;
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("isAllSubActHaveSubmission throws error!");
		} finally {
			DBUtils.close(conn);
		}
		return flag;
	}

	/**
	 * 查询审批步骤目前上报上来的子节点的个数 用来判断该审批步骤下是否所有的子节点都已经上报了数据
	 * 
	 * @param actId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private int getCountPreAct(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select count(distinct pre_act_id) c from dc_approve_work where act_id = ? ")
				.append(
						" and aw_state <> 0 and aw_state <> 1 and aw_state <> 2 and aw_state <> 3")
				.append(
						" and aw_state <> 6 and aw_state <> 7 and aw_state <> 8 and aw_state <> 9");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityComplete error!");
		}
		return count;
	}

	/**
	 * 计算在流程实例中该步骤下的子节点的个数
	 * 
	 * @param actId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private int getCountSubActInProcess(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("select count(distinct id) c from dc_proc_instance where para_id = ? ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityComplete error!");
		}
		return count;
	}

	public int getActivityType(String actId) throws DaoException {
		String sql = "select distinct(aw_type) from dc_approve_work where act_id = ?";
		QueryOperator query = new QueryOperator();
		query.setSql(sql);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int swType = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					swType = rs.getFieldValueAsInteger("aw_type").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getActivityType error!");
		}

		return swType;
	}

	/**
	 * 得到处于等待状态的用户个数
	 * 
	 * @param actId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private int getCountActivityWaiting(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(id) c from dc_approve_work where act_id = ? ")
				.append("  and aw_state = 2 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityWaiting error!");
		}
		return count;
	}

	/**
	 * 该步骤审批人员的个数
	 * 
	 * @param actId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private int getCountActivityTotalUser(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("select count(id) c from dc_approve_work where act_id = ? and aw_state <> 8 and  aw_state <> 6 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityTotalUser error!");
		}
		return count;
	}

	public boolean saveApproveInfo(ApproveWorkItem aw) throws DaoException {
		UpdateOperator update = new UpdateOperator();
		if (aw.getApproveMindType() == Constants.APPROVE_MIND_TYPE_AGRREE) {
			StringBuffer sql = new StringBuffer();
			sql
					.append(
							"update dc_approve_work set approve_info=?,approve_mind_date=sysdate,")
					.append(
							"approve_mind_type=?,approve_subwork=(select submi_user from dc_approve_work ")
					.append(" where id =?) where id=?");

			update.setSql(sql.toString());
			update.addParameter(new SqlParameter(SqlType.VARCHAR, aw
					.getApproveInfo()));
			update.addParameter(new SqlParameter(SqlType.INTEGER, new Integer(
					aw.getApproveMindType())));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, aw.getId()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, aw.getId()));
		} else {
			StringBuffer sql = new StringBuffer();
			sql
					.append(
							"update dc_approve_work set approve_info=?,approve_mind_date=sysdate,")
					.append("approve_mind_type=?,approve_subwork=? where id=?");

			update.setSql(sql.toString());
			update.addParameter(new SqlParameter(SqlType.VARCHAR, aw
					.getApproveInfo()));
			update.addParameter(new SqlParameter(SqlType.INTEGER, new Integer(
					aw.getApproveMindType())));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, aw
					.getApproveSubwork()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, aw.getId()));
		}

		try {
			update.access();
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存ID为：" + aw.getId() + " 的审批意见出错！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "审批意见信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "审批意见信息"
						+ Constants.FAIL);
			}
			return false;
		}
	}

	public ApproveWorkItem getByKey(String id) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select id,proc_id,aw_desc,aw_name,act_id,aw_state,aw_type,staff_id,date_approve, ")
				.append(
						" approve_info,approve_mind_date,approve_mind_type,submi_user,state_track,pre_act_id,")
				.append(
						"pre_act_type,approve_subwork,form_id from dc_approve_work where id=?");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, id));
		ApproveWorkItem awi = new ApproveWorkItem();
		try {
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					awi.setId(rs.getFieldValueAsString("id"));
					awi.setProcId(rs.getFieldValueAsString("proc_id"));
					awi.setTaskDesc(rs.getFieldValueAsString("aw_desc"));
					awi.setTaskName(rs.getFieldValueAsString("aw_name"));
					awi.setActId(rs.getFieldValueAsString("act_id"));
					awi.setState(rs.getFieldValueAsInteger("aw_state")
							.intValue());
					awi
							.setType(rs.getFieldValueAsInteger("aw_type")
									.intValue());
					awi.setStaffId(rs.getFieldValueAsString("staff_id"));
					String timelimitStr = Format.getInstance().dateToYMD(
							rs.getFieldValueAsDate("date_approve"));
					awi.setTimeLimitStr(timelimitStr);
					awi
							.setApproveInfo(rs
									.getFieldValueAsString("approve_info"));
					String approveMindDateStr = Format.getInstance().dateToYMD(
							rs.getFieldValueAsDate("approve_mind_date"));
					awi.setApproveMindDateStr(approveMindDateStr);
					int type = rs.getFieldValueAsInteger("approve_mind_type") == null ? 0
							: rs.getFieldValueAsInteger("approve_mind_type")
									.intValue();
					awi.setApproveMindType(type);
					awi.setSubmiUser(rs.getFieldValueAsString("submi_user"));
					awi.setPreActId(rs.getFieldValueAsString("pre_act_id"));
					awi.setPreActType(rs.getFieldValueAsInteger("pre_act_type")
							.intValue());
					awi.setApproveSubwork(rs
							.getFieldValueAsString("approve_subwork"));
					awi.setFormId(rs.getFieldValueAsString("form_id"));

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("获取ID为：" + id + " 的审批明细出错！");
		}
		return awi;
	}

	public int getApporveMindType(String id) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		StringBuffer sql = new StringBuffer();
		sql
				.append("select approve_mind_type from dc_approve_work where id = ? ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, id));
		int type = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					type = rs.getFieldValueAsInteger("approve_mind_type")
							.intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getApporveMindType throw error!");
		}
		return type;
	}

	private List getApproveInfoHistory4SubmissionActivity(String swId)
			throws DaoException {
		logger.debug(Constants.INTOMETHOD
				+ "getApproveInfoHistory4SubmissionActivity");
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select a.id,a.aw_name,a.approve_info,a.approve_mind_date,a.approve_mind_type,")
				.append(
						"a.submi_user,a.pre_act_type,f.user_name from dc_approve_work a ")
				.append(
						" left join frameuser f on a.staff_id=f.user_code where a.submi_user= ? where aw_state = 9");
		Connection conn = null;

		List historyInfoes = null;
		try {
			conn = this.getConnection();
			historyInfoes = new ArrayList();

			QueryOperator query = new QueryOperator();
			query.setUseOnlyConnectionFlag(true);
			query.setPresentConnection(conn);
			query.setSql(sql.toString());
			query.addParameter(new SqlParameter(SqlType.VARCHAR, swId));

			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					ApproveWorkItem awi = new ApproveWorkItem();
					awi.setId(rs.getFieldValueAsString("id"));
					awi.setTaskName(rs.getFieldValueAsString("aw_name"));
					awi.setStaffId(rs.getFieldValueAsString("user_name"));
					awi
							.setApproveInfo(rs
									.getFieldValueAsString("approve_info"));
					String approveMindDateStr = Format.getInstance().dateToYMD(
							rs.getFieldValueAsDate("approve_mind_date"));
					awi.setApproveMindDateStr(approveMindDateStr);
					int type = rs.getFieldValueAsInteger("approve_mind_type") == null ? 0
							: rs.getFieldValueAsInteger("approve_mind_type")
									.intValue();
					awi.setApproveMindType(type);

					String submiActId = rs.getFieldValueAsString("submi_user");
					int preActType = rs.getFieldValueAsInteger("pre_act_type")
							.intValue();
					String userName = this.getSubmiUserName(submiActId,
							preActType, conn);
					awi.setSubmiUser(userName);

					historyInfoes.add(awi);
				}
				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("approveInfoHistory throw error!");
		} finally {
			DBUtils.close(conn);
		}
		return historyInfoes;

	}

	public List approveInfoHistory(String actId, int type) throws DaoException {
		List approveInfos = new ArrayList();
		if (type == Constants.APPROVE_STEP_TYPE) {
			approveInfos = this.getApproveInfoHistory4ApproveActivity(actId);
		} else if (type == Constants.COLLECTION_STEP_TYPE) {
			approveInfos = this.getApproveInfoHistory4SubmissionActivity(actId);
		}
		return approveInfos;
	}

	private List getApproveInfoHistory4ApproveActivity(String actId)
			throws DaoException {
		logger.debug(Constants.INTOMETHOD
				+ "getApproveInfoHistory4ApproveActivity");
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select a.id,a.aw_name,a.approve_info,a.approve_mind_date,a.approve_mind_type,")
				.append(
						"a.submi_user,a.pre_act_type,f.user_name from dc_approve_work a left join frameuser f ")
				.append(
						"  on a.staff_id=f.user_code where a.act_id= ? and aw_state <> 8 and aw_state <> 1")
				.append(
						"  and aw_state <> 3 and aw_state <> 6 and aw_state <> 7 and aw_state <> 0");
		Connection conn = null;

		List historyInfoes = null;
		try {
			conn = this.getConnection();
			// 得到该审批步骤下所有的审批步骤类型的子环节
			List actIds = this.allApproveActivityChildren(actId, conn);
			actIds.add(actId);
			historyInfoes = new ArrayList();

			for (Iterator iter = actIds.iterator(); iter.hasNext();) {
				String id = (String) iter.next();
				QueryOperator query = new QueryOperator();
				query.setUseOnlyConnectionFlag(true);
				query.setPresentConnection(conn);
				query.setSql(sql.toString());
				query.addParameter(new SqlParameter(SqlType.VARCHAR, id));

				query.access();
				if (query.resultSetAvailable()) {
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());

					for (int i = 0; i < rs.rowCount; i++) {
						ApproveWorkItem awi = new ApproveWorkItem();
						awi.setId(rs.getFieldValueAsString("id"));
						awi.setTaskName(rs.getFieldValueAsString("aw_name"));
						awi.setStaffId(rs.getFieldValueAsString("user_name"));
						awi.setApproveInfo(rs
								.getFieldValueAsString("approve_info"));
						String approveMindDateStr = Format
								.getInstance()
								.dateToYMD(
										rs
												.getFieldValueAsDate("approve_mind_date"));
						awi.setApproveMindDateStr(approveMindDateStr);
						int type = rs
								.getFieldValueAsInteger("approve_mind_type") == null ? 0
								: rs
										.getFieldValueAsInteger(
												"approve_mind_type").intValue();
						awi.setApproveMindType(type);

						String submiActId = rs
								.getFieldValueAsString("submi_user");
						int preActType = rs.getFieldValueAsInteger(
								"pre_act_type").intValue();
						String userName = this.getSubmiUserName(submiActId,
								preActType, conn);
						awi.setSubmiUser(userName);

						historyInfoes.add(awi);

						rs.next();
					}

					rs.clearAll();
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("approveInfoHistory throw error!");
		} finally {
			DBUtils.close(conn);
		}
		return historyInfoes;

	}

	private String getSubmiUserName(String submiUserIds, int actType,
			Connection conn) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(submiUserIds)) {
			String[] args = { "submiUserIds" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter submiUserIds NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		StringBuffer sql = new StringBuffer();
		if (actType == Constants.APPROVE_STEP_TYPE) {
			sql
					.append(
							"select f.user_name from dc_approve_work a left join ")
					.append(
							" frameuser f on a.staff_id = f.user_code where a.id = ?");

		} else if (actType == Constants.COLLECTION_STEP_TYPE) {
			sql
					.append(
							"select f.user_name from dc_submission_work s left join ")
					.append(
							" frameuser f on s.staff_id = f.user_code where s.id = ?");
		}

		String[] submiUsers = StringUtils.split(submiUserIds, ",");
		StringBuffer userNames = new StringBuffer();

		try {
			for (int i = 0; i < submiUsers.length; i++) {
				String subId = submiUsers[i];

				QueryOperator query = new QueryOperator();
				query.setUseOnlyConnectionFlag(true);
				query.setPresentConnection(conn);
				query.setSql(sql.toString());
				query.addParameter(new SqlParameter(SqlType.VARCHAR, subId));

				query.access();
				if (query.resultSetAvailable()) {
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());
					if (rs.rowCount > 0) {
						String userName = rs.getFieldValueAsString("user_name");
						if (StringUtils.isEmpty(userNames.toString())) {
							userNames.append(userName);
						} else {
							userNames.append(",").append(userName);
						}
					}

					rs.clearAll();
				}
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("userName throw error!");
		}
		return userNames.toString();

	}

	/**
	 * 查找id为actId 下的所有审批步骤节点id
	 * 
	 * @param actId
	 * @return
	 * @throws DaoException
	 */
	private List allApproveActivityChildren(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("select id from dc_proc_instance where para_id = ? and act_type = 1");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		List approveChildren = null;
		try {
			approveChildren = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					String id = rs.getFieldValueAsString("id");
					approveChildren.add(id);
					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("allApproveActivityChildren throw error!", e);
			throw new DaoException("查找id为：" + actId + " 下的所有审批步骤节点id出错！");
		}
		return approveChildren;
	}

	public List getSubWorkUsers(String approveWorkId) throws DaoException {
		ApproveWorkItem awi = this.getByKey(approveWorkId);
		List subWorkUsers = new ArrayList();
		Connection conn = null;
		try {
			if (awi != null) {
				conn = this.getConnection();
				String submiUser = awi.getSubmiUser();
				String[] submiUsers = StringUtils.split(submiUser, ",");
				StringBuffer sql = new StringBuffer();
				sql
						.append(
								"select f.user_name from dc_submission_work s left join ")
						.append(
								" frameuser f on s.staff_id = f.user_code where s.id = ?");
				for (int i = 0; i < submiUsers.length; i++) {
					String subworkId = submiUsers[i];
					QueryOperator query = new QueryOperator();
					query.setUseOnlyConnectionFlag(true);
					query.setPresentConnection(conn);
					query.setSql(sql.toString());
					query.addParameter(new SqlParameter(SqlType.VARCHAR,
							subworkId));

					query.access();
					if (query.resultSetAvailable()) {
						// 获取并处理记录集
						RsDataSet rs = new RsDataSet(query.getSqlResultSet());
						if (rs.rowCount > 0) {
							String subWorkUserName = rs
									.getFieldValueAsString("user_name");
							ApproveSubWork asw = new ApproveSubWork();
							asw.setSubUserName(subWorkUserName);
							asw.setSubWorkId(subworkId);

							subWorkUsers.add(asw);
						}

						rs.clearAll();
					}
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getSubWorkUsers throw error!");
		} finally {
			DBUtils.close(conn);
		}
		return subWorkUsers;

	}

	/**
	 * 得到某个环节下所有的处于汇聚同步等待状态的审批任务id
	 * 
	 * @param actId
	 * @return
	 * @throws DaoException
	 */
	public String getAllApproveWorkIds(String actId) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select id from dc_approve_work where act_id = ? and aw_state <>0 ")
				.append(
						" and aw_state <>3 and aw_state <>6 and aw_state <>7 and aw_state <>8 ");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		StringBuffer awIds = new StringBuffer();
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());

				for (int i = 0; i < rs.rowCount; i++) {
					String id = rs.getFieldValueAsString("id");
					if (StringUtils.isEmpty(awIds.toString())) {
						awIds.append(id);
					} else {
						awIds.append(",").append(id);
					}

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getAllApproveWorkIds throw error!");
		}
		return awIds.toString();
	}

	/**
	 * 获取审批任务明细
	 * 
	 * @param activityId
	 * @return
	 * @throws DaoException
	 */
	public List findApproveWorkDetailByActivityId(String activityId)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select a.id,a.staff_id,a.aw_state,f.user_name  from dc_approve_work a ")
				.append(
						" left join frameuser f on a.staff_id=f.user_code  where a.act_id = ? where a.aw_state <> 8");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, activityId));
		List list = null;
		try {
			list = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					RoleTreeNode treeNode = new RoleTreeNode();
					String id = rs.getFieldValueAsString("id");
					treeNode.setId(id);
					int state = rs.getFieldValueAsInteger("aw_state")
							.intValue();
					String stateStr = "";
					switch (state) {
					case 1:
						stateStr = "已填写未提交";
						break;
					case 2:
						stateStr = "等待其他人";
						break;
					case 3:
						stateStr = "超时未完成";
						break;
					case 4:
						stateStr = "等待审批中";
						break;
					case 5:
						stateStr = "完成审批";
						break;
					default:
						stateStr = "未处理";
						break;
					}
					String userName = rs.getFieldValueAsString("user_name");
					String text = userName + "&lt;" + stateStr + "&gt;";
					treeNode.setText(text);
					treeNode.setLeaf(true);
					treeNode.setIconCls("workGroup");

					list.add(treeNode);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("findApproveWorkIdByProcId error!");
		}
		return list;
	}

}
